package com.wjl.picture.common.config;

import com.wjl.picture.wx.constant.WxMpConstant;
import com.wjl.picture.wx.handler.*;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT;

@Configuration
public class WxMpConfig {
    @Resource
    LogHandler logHandler;
    @Resource
    SubscribeHandler subscribeHandler;
    @Resource
    ScanHandler scanHandler;
    @Resource
    MsgHandler msgHandler;
    @Resource
    EventHandler eventHandler;

    @Bean
    public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);

        // 记录所有事件的日志 （异步执行）
        newRouter
                .rule()
                .handler(this.logHandler)
                .next();

        // 关注事件
        newRouter
                .rule()
                .async(false)
                .msgType(EVENT)
                .event(SUBSCRIBE)
                .handler(this.subscribeHandler).end();

        // 扫码事件
        newRouter
                .rule()
                .async(false)
                .msgType(EVENT)
                .event(WxConsts.EventType.SCAN)
                .handler(this.scanHandler).end();

        newRouter
                .rule()
                .async(false)
                .msgType(WxConsts.XmlMsgType.EVENT)
                .event(WxConsts.EventType.CLICK)
                .eventKey(WxMpConstant.CLICK_MENU_KEY)
                .handler(eventHandler).end();

        // 默认
        newRouter
                .rule()
                .async(false)
                .handler(this.msgHandler).end();


        return newRouter;
    }
}
